package com.ocom.human.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.HumanServiceUrl;
import com.ocom.common.constant.UserConstants;
import com.ocom.common.dto.AddDeptDto;
import com.ocom.common.dto.DeleteDeptDto;
import com.ocom.common.dto.Department;
import com.ocom.common.dto.ModifyDeptDto;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.human.GetDeptByIdsRequest;
import com.ocom.common.request.human.GetDeptIdByFullNameRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.human.service.CompanyListService;
import com.ocom.human.service.DeptInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class DeptInfoController {
    private final Logger log = LoggerFactory.getLogger(DeptInfoController.class);

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private CompanyListService companyListService;




    /**
     * 获取部门列表
     * @param comID 单位编号
     * @param deptID 部门编号
     * */
    @GetMapping(HumanServiceUrl.URL_Department_GetDeptInfo)
    public Result GetDeptInfo(Long comID, Long deptID,String deptName ){
        log.info("comID{{}},deptID{{}},deptName{{}}",comID,deptID,deptName);
        List<EntityDeptInfo> entityDeptInfos = deptInfoService.GetDeptInfo(comID, deptID, deptName);
        log.info("entityDeptInfos{{}}",entityDeptInfos);
        EntityCompanyList entityCompanyList = companyListService.selectById(comID);

        if (StringUtils.isNull(deptID)){
            log.info("entityCompanyList{{}}",entityCompanyList);
            EntityDeptInfo entityDeptInfo = new EntityDeptInfo();
            entityDeptInfo.setComId(entityCompanyList.getComId());
            entityDeptInfo.setDeptId(0L);
            entityDeptInfo.setDeptNo(1L);
            entityDeptInfo.setParentDeptId(0L);
            entityDeptInfo.setGrade(0L);
            entityDeptInfo.setDeptName(entityCompanyList.getComName());
            entityDeptInfo.setCreateTime(entityCompanyList.getCreateTime());
            entityDeptInfo.setUpdateTime(entityCompanyList.getUpdateTime());
            entityDeptInfo.setRemark(entityCompanyList.getRemark());
            entityDeptInfos.add(entityDeptInfo);
            log.info("entityDeptInfos{{}}",entityDeptInfos);
        }

        return ResultUtil.success(entityDeptInfos);
    }

    /**
     * 部门树列表
     * @param companyId
     * @param deptId
     * @return
     */
    @PostMapping(HumanServiceUrl.URL_Department_GetDeptList)
    public Result<List<EntityDeptInfo>> getDeptList(Long companyId, Long deptId,Integer show){
        List<EntityDeptInfo> entityDeptInfos = deptInfoService.getDeptList(companyId,deptId);
        EntityCompanyList entityCompanyList = companyListService.selectById(companyId);
        if(entityDeptInfos==null)  entityDeptInfos=new ArrayList<>();
        if(show==1){
            EntityDeptInfo entityDeptInfo = new EntityDeptInfo();
            entityDeptInfo.setComId(entityCompanyList.getComId());
            entityDeptInfo.setDeptId(0L);
            entityDeptInfo.setDeptNo(1L);
            entityDeptInfo.setParentDeptId(0L);
            entityDeptInfo.setGrade(0L);
            entityDeptInfo.setDeptName(entityCompanyList.getComName());
            entityDeptInfo.setCreateTime(entityCompanyList.getCreateTime());
            entityDeptInfo.setUpdateTime(entityCompanyList.getUpdateTime());
            entityDeptInfo.setRemark(entityCompanyList.getRemark());
            entityDeptInfos.add(entityDeptInfo);
        }
        return ResultUtil.success(entityDeptInfos);
    }



    /***
     * 新增部门
     * @param addDeptDto 对象
     */
    @PostMapping(HumanServiceUrl.URL_Department_AddDeptInfo)
    public Result AddDeptInfo(@Validated @RequestBody AddDeptDto addDeptDto){
        if (UserConstants.NOT_UNIQUE.equals(deptInfoService.AddDeptNameUnique(addDeptDto.getComId(),addDeptDto.getDeptName(),addDeptDto.getParentDeptId())))
        {
            log.error("部门名称已存在");
            return ResultUtil.error(ResultEnum.Err_308);
        }
        Long deptId = deptInfoService.insertDept(addDeptDto,addDeptDto.getComId());
        return ResultUtil.success(deptId);
    }
    /**修改部门*/
    @PostMapping(HumanServiceUrl.URL_Department_UpdateDept)
    public Result UpdateDept(@Validated @RequestBody ModifyDeptDto modifyDeptDto){
        if (UserConstants.NOT_UNIQUE.equals(deptInfoService.UpdateDeptNameUnique(modifyDeptDto,modifyDeptDto.getComId())))
        {
            log.error("部门名称已存在");
            return ResultUtil.error(ResultEnum.Err_308);
        }

        deptInfoService.UpdateDept(modifyDeptDto,modifyDeptDto.getComId());
        return ResultUtil.success();
    }

    /**删除部门*/
    @PostMapping(HumanServiceUrl.URL_Department_DelDept)
    public Result DelDept(@Validated @RequestBody DeleteDeptDto deleteDeptDto){
        //部门下有子级不允许删除
        if (deptInfoService.hasChildByDeptId(deleteDeptDto.getComId(),deleteDeptDto.getDeptId())){
            log.error("存在子部门，不可删除");
           return ResultUtil.error(ResultEnum.Err_309);
        }

        //部门下有人员不允许删除
        if (deptInfoService.checkDeptExistUser(deleteDeptDto.getComId(),deleteDeptDto.getDeptId())){
            return ResultUtil.error(ResultEnum.Err_310);
        }

        deptInfoService.DelDept(deleteDeptDto.getComId(),deleteDeptDto.getDeptId());
        return ResultUtil.success();
    }


    /*
     * @Description:2.1.6获取下级部门信息
     * @Author: lu 
     * @Date: 2022/4/21 15:35
     * @param deleteDeptDto:  
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(HumanServiceUrl.URL_DepartmentGetDeptInfos)
    public Result departmentGetDeptInfos(@Validated @RequestBody Department department){
        log.info("获取下级部门信息請求參數:{{}}",department);
        if (department.getComId()==null){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        PageInfo<EntityDeptInfo> list=deptInfoService.selectGetDeptInfos(department.getComId(),department);
        JSONArray jsonArray= JSON.parseArray(JSON.toJSONString(list.getList()));
        JSONObject reObject=new JSONObject();
        reObject.put("total",list.getTotal());
        reObject.put("list",jsonArray);
        return ResultUtil.success(reObject);
    }

    /*
     * @Description:2.1.5获取部门id（department/getDeptIds）
     * @Author: lu 
     * @Date: 2022/4/22 10:30
     * @param department:  
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(HumanServiceUrl.URL_DepartmentGetDeptIds)
    public Result getDeptIds(@Validated @RequestBody Department department){
        log.info("获取部门id請求參數:{{}}",department);
        if (department.getComId()==null || department.getDeptId()==null){
            return ResultUtil.error(ResultEnum.Err_203);
        }

        String bootparentDeptId=deptInfoService.selectDeptIds(department.getComId(),department);
        JSONObject reObject=new JSONObject();
        reObject.put("comId",department.getComId());
        reObject.put("deptId",department.getDeptId());
        reObject.put("deptIds",bootparentDeptId);
        return ResultUtil.success(reObject);
    }

    /**
     *@Description:批量添加部门
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2023/2/15 9:49       
     */
    @PostMapping(HumanServiceUrl.URL_departmentAddDepts)
    public Result departmentAddDepts(@RequestBody JSONObject jsonObject){
        List<EntityDeptInfo> entityDeptInfos = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")),EntityDeptInfo.class);
        if (deptInfoService.saveArr(jsonObject.getLong("comId"),entityDeptInfos)){
            return ResultUtil.success();
        }else {
            return ResultUtil.error(ResultEnum.Err_2016);
        }
    }

    @PostMapping(HumanServiceUrl.URL_getDeptIdByFullName)
    public Result getDeptIdByFullName(@RequestBody GetDeptIdByFullNameRequest request){
        HashMap<String, Object> map = new HashMap<>();
        Long deptId = 0l;
        String deptName = "";
        if (StringUtils.isNotBlank(request.getDeptFullName())) {

            try {
                //获取完整部门树
                List<EntityDeptInfo> list = deptInfoService.getDeptList(request.getComId(), null);
                String[] deptNameSplit = request.getDeptFullName().split("/");

                Long realDeptId = 0l;
                Long parentDeptId = 0l;
                outterLoop:
                for (String ndeptName : deptNameSplit) {
                    Boolean exist = false;
                    deptName = ndeptName;
                    for (EntityDeptInfo entityDeptInfo : list) {
                        //匹配到名称
                        if (entityDeptInfo.getDeptName().equals(ndeptName) && entityDeptInfo.getParentDeptId().equals(parentDeptId)) {
                            exist = true;
                            deptName = null;
                            parentDeptId = entityDeptInfo.getDeptId();
                            realDeptId = entityDeptInfo.getDeptId();
                            break;
                        }
                    }
                    //匹配不到 跳出循环
                    if (!exist) {
                        break outterLoop;
                    }
                }
                deptId = realDeptId;
            } catch (Exception e) {
                log.info("部门匹配异常【{}】 【{}】", request, e);
            }
        }
        map.put("deptId", deptId);
        map.put("failDept", deptName);
        return ResultUtil.success(map);
    }


    @PostMapping(HumanServiceUrl.URL_getDeptById)
    public Result getDeptById(@RequestBody EntityDeptInfo entityDeptInfo){
        entityDeptInfo = this.deptInfoService.SelectDeptName(entityDeptInfo.getDeptId(),entityDeptInfo.getComId());
        return ResultUtil.success(entityDeptInfo);
    }

    @PostMapping(HumanServiceUrl.URL_getDeptByIds)
    public Result getDeptByIds(@RequestBody GetDeptByIdsRequest request){
        return ResultUtil.success(this.deptInfoService.getByIds(request.getComId(),request.getIds()));
    }
}


